package cc.bluemc.modules.adminUser.service;

import cc.bluemc.modules.adminUser.entity.AdminUser;
import cc.bluemc.modules.adminUser.entity.Permission;
import cc.bluemc.platform.comm.Pagination;
import cc.bluemc.platform.jdbctemplatetool.JdbcTemplateTool;
import cc.bluemc.platform.jdbctemplatetool.exception.NoColumnAnnotationFoundException;
import cc.bluemc.platform.jdbctemplatetool.exception.NoIdAnnotationFoundException;
import cc.bluemc.platform.utils.Md5Util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * 系统用户
 * @author Administrator
 *
 */
@Service
@Transactional
public class AdminUserService {
	
	private Log log = LogFactory.getLog(this.getClass());
	@Autowired
	private JdbcTemplateTool jdbcTemplateTool;
	@Autowired
	private SessionDAO sessionDAO;

	
	/**
	 * 在线用户统计
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public Collection<Session> getActiveSessions(){
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		return sessions;
	}
	
	/**
	 * 修改用户
	 */
	@Transactional(readOnly=false)
	public void updateBean(AdminUser user,Integer [] roleIds) throws Exception{
		jdbcTemplateTool.update(user);
		if(null!=roleIds&&roleIds.length>0){
			setRole(user.getId(),roleIds);
		}
	}
	
	/**
	 * 保存用户
	 * @param entiy
	 * @return
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	public int save(AdminUser entiy,Integer [] roleIds) throws Exception {
		entiy.setPassword(Md5Util.encryptPassword(entiy.getUserName(), entiy.getPassword(), entiy.getSalt()));
		int id =jdbcTemplateTool.save(entiy,"id");
		if(null!=roleIds&&roleIds.length>0){
			setRole(id,roleIds);
		}
		return id;
	}
	
	
	
	/**
	 * 根据ID获得用户
	 * @param id
	 * @return
	 * @throws NoIdAnnotationFoundException
	 * @throws NoColumnAnnotationFoundException
	 */
	public AdminUser getAdminUser(int id) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		return jdbcTemplateTool.get(AdminUser.class, id);
	}
	/**
	 * 根据用户名获得用户
	 * @param userName
	 * @return
	 * @throws NoIdAnnotationFoundException
	 * @throws NoColumnAnnotationFoundException
	 */
	public AdminUser getAdminUser(String userName) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		return jdbcTemplateTool.get(" user_name=? ", new Object[]{userName}, AdminUser.class);
	}
	/**
	 * 根据用户名获得用户
	 * @param userName
	 * @param pwd
	 * @return
	 * @throws NoIdAnnotationFoundException
	 * @throws NoColumnAnnotationFoundException
	 */
	public AdminUser getAdminUser(String userName,String pwd) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		return jdbcTemplateTool.get(" user_name=? AND password=?", new Object[]{userName,pwd}, AdminUser.class);
	}
	/**
	 * 分页查找用户
	 * @param page
	 * @return
	 */
	public Pagination getList(Pagination page){
		String sql="SELECT * FROM t_admin_user LIMIT ?,?";
		int count = jdbcTemplateTool.count("select count(0) from t_admin_user", new Object[]{});
		page.setTotalResults((long)count);
		Object[] params = new Object[]{page.getFirstResult(),page.getPageSize()};
		List<AdminUser> list= jdbcTemplateTool.list(sql,params ,AdminUser.class);
		page.setDatas(list);
		return page;
	}
	/**
	 * 为用户设置分配角色
	 * @param userId
	 * @param roleIds
	 */
	private void setRole(final int userId,final Integer [] roleIds){
		JdbcTemplate jdbcTemplate = jdbcTemplateTool.getJdbcTemplate();
		jdbcTemplate.update("DELETE FROM t_adminuser_role WHERE userId=?", new Object[]{userId});
		if(null!=roleIds){
			jdbcTemplate.batchUpdate("insert into t_adminuser_role (userId, roleId) values (?, ?)", new BatchPreparedStatementSetter(){
				@Override
				public int getBatchSize() {
					return roleIds.length;
				}
				@Override
				public void setValues(PreparedStatement arg0, int arg1)
				throws SQLException {
					arg0.setInt(1, userId);
					arg0.setInt(2, roleIds[arg1]);
				}
				
			});
		}
	}
	/**
	 * 获取用户权限
	 * @param userId
	 * @return
	 */
	public List<Permission> getUserPermissions(int userId){
		String sql="SELECT p.* FROM t_permission p " +
				"LEFT JOIN t_role_perm rp ON p.id = rp.permId " +
				"LEFT JOIN t_adminuser_role ar ON rp.roleId = ar.roleId " +
				"LEFT JOIN t_role r ON r.id= ar.roleId " +
				"WHERE ar.userId=? AND r.usable=1";
		List<Permission> list= jdbcTemplateTool.list(sql,new Object[]{userId} ,Permission.class);
		return list;
	}
}
